package unsafeExp;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: javase
 * @description: 不安全的集合
 * @author: lld
 * @create: 2021-03-21 20:11
 **/
public class UnsafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        for (int i = 0; i < 1000; i++) {
            //同步代码块
            new Thread(() -> {
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
            }).start();

            //不安全
//            new Thread(()-> list.add(Thread.currentThread().getName())).start();
            //相当于
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    list.add(Thread.currentThread().getName());
//                }
//            });
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
